package com.jm.product.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jm.product.entity.Brand;
import com.jm.product.utils.UploadFileUtils;

/**
 * 商品品牌Controller
 * @author sunshine
 * @version 2017-07-03
 */
@Controller
@RequestMapping(value = "product/brand")
public class BrandController extends com.jm.product.controller.core.BaseController<Brand,Integer> {

	private static final String SUB_UPLOAD_FOLDER = "brand";
	
	protected String listPage() {

		return "product/brandList";
	}

	public String form(Brand brand, Model model) {
		/*
		if (null != brand && null != brand.getId()){
			this.data = service.getById(brand.getId());
			model.addAttribute("brand", this.data);
		}
		*/
		model.addAttribute("brand", this.data);
		return "product/brandForm";
	}
	
	@Override
	public String save(Brand data, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (request instanceof MultipartHttpServletRequest) {
			// 对文件进处理
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            String uploadRootPath = session.getServletContext().getRealPath("/") ;
            String uploadFolder = this.uploadPath + "/" + SUB_UPLOAD_FOLDER ;
            // 获取上传的文件
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){
                try {
                	//TODO:这里可改为云存储，目前暂存储在项目目录下
                	String filePath = UploadFileUtils.upload(entry.getValue(), uploadRootPath, uploadFolder);
					data.setLogo(filePath);
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
        }
		data.setDisabled("0");
		return super.save(data, model, redirectAttributes, request);
	}
	
	public String savePage() {

		return "redirect:/product/brand/?repage";
	}

}
